package com.tianhaochen.springai.config;

import lombok.RequiredArgsConstructor;
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.ai.chat.messages.Message;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.List;

@RequiredArgsConstructor
@Component
public class RedisChatMemory implements ChatMemory {
    private final static String REDIS_KEY = "chat:memory";
    private final RedisTemplate<String, Message> redisTemplate;

    @Override
    public void add(String conversationId, List<Message> messages) {
        redisTemplate.opsForList().leftPushAll(REDIS_KEY + conversationId, messages);
    }

    public List<Message> get(String conversationId, int lastN) {
        return redisTemplate.opsForList().range(REDIS_KEY + conversationId, -lastN, -1);
    }

    @Override
    public void clear(String conversationId) {
        redisTemplate.delete(REDIS_KEY + conversationId);
    }
}
